const app = getApp();
const Controller = require('../../controllers/controllers').controller;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: 'TA的主页',
    isselect: false,
    albumnavcurrent: 1,
    userInfo: '',
    userInfodata: '',
    userId: '',
    isown: false,
    audioListdata: [],
    page: 1,
    pageSize: 10,
    isEnd: false,
    ids: [],
    isallselect: false,
  },
  goToCommentDetail(e) {
    console.log('跳转到评论详情页', e)
    let commentId = e.currentTarget.dataset.commentid
    let bodyId = e.currentTarget.dataset.bodyid
    let bodyType = e.currentTarget.dataset.bodytype
    let action = e.currentTarget.dataset.action
    if (action == 3) {
      // 音频的id（或者栏目，合辑等的id） 音频的（或者栏目，合辑等的type）type bodyId
      wx.navigateTo({
        url: '/pages/Comment/Comment?rid=' + bodyId + '&type=' + bodyType,
      })
    }
  }, 
  onReady() {
    this.Dialog = this.selectComponent('#Dialog');
  },
  // 播放全部
  playall(e) {
    var index=0;
    if(e.currentTarget.dataset.index){
      index=e.currentTarget.dataset.index
    }
    app.globalData.currentIndex=index
    app.globalData.songlist=this.data.audioListdata
    // this._init()
    wx.navigateTo({
      url: "/pages/Playing/Playing?albumnavcurrent=" + (this.data.albumnavcurrent==1?2:0) + "&userId=" + this.data.userId + "&currentIndex=" + index
    })
  },
  onLoad: function (options) {
    console.log('options', options)
    if (options) {
      this.setData({
        userId: options.id,
        userInfo: wx.getStorageSync('userInfo')
      })
      this.getUserInfo()
      this.historyList()
    }

  },
  getUserInfo() {
    Controller.getUserInfo({
      userId: this.data.userId
    }).then(res => {
      this.setData({
        userInfodata: res.data.baseData
      })
      if (this.data.userInfodata.id == this.data.userInfo.id) {
        this.setData({
          isown: true,
          title: "我的主页",
        })
      } else { 
        this.setData({
          isown: false,
          title: "TA的主页",
        })
      }
    });
  },
  albumnav(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      albumnavcurrent: index,
      audioListdata: [],
      ids: [],
      page: 1,
      pageSize: 10,
      isEnd: false,
      isallselect: false,
      isselect: false
    })
    this.historyList()
  },
  historyList() {
    if (this.data.albumnavcurrent == 1) {
      Controller.historyList({
        userId: this.data.userId,
        page: this.data.page,
        pageSize: this.data.pageSize,
      }).then(res => {
        if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
          for (let item of res.data.baseData.list) {
            item.select = 0;
          }
          this.setData({
            audioListdata: this.data.audioListdata.concat(res.data.baseData.list)
          })
          if (res.data.baseData.lastPage) {
            this.setData({
              isEnd: true
            })
          }
        }
      })
    }
    if (this.data.albumnavcurrent == 2) {
      Controller.collectList({
        userId: this.data.userId,
        page: this.data.page,
        pageSize: this.data.pageSize,
      }).then(res => {
        if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
          this.setData({
            audioListdata: this.data.audioListdata.concat(res.data.baseData.list)
          })
          if (res.data.baseData.lastPage) {
            this.setData({
              isEnd: true
            })
          }
        }
      })
    }
    if (this.data.albumnavcurrent == 3) {
      let data = {}
      if (this.data.userId != this.data.userInfo.id) {
        console.log('他人')
        // 他人
        data = {
          userId: this.data.userId,
          page: this.data.page,
          pageSize: this.data.pageSize,
        }
      } else {
        // 是自己
        data = {
          page: this.data.page,
          pageSize: this.data.pageSize,
        }
      }
      Controller.userActionList(data).then(res => {
        if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
          this.setData({
            audioListdata: this.data.audioListdata.concat(res.data.baseData.list)
          })
          if (res.data.baseData.lastPage) {
            this.setData({
              isEnd: true
            })
          }
        }
      })
    }

  },
  scrollend: function () {
    if (this.data.isEnd) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1,
      });
      this.historyList()
    }
  },
  delete() {
    var content = ""
    if (this.data.albumnavcurrent == 1) {
      content = "删除选中的音频不可恢复"
    } else {
      content = "确定取消选中的关注？"
    }
    this.Dialog.ShowDialog({
      type: 'Confirm',
      title: content,
      btnArray: [{
          title: '取消',
          name: 'cancel',
          class: ''
        },
        {
          title: '确定',
          name: 'confirm',
          class: 'confirm'
        }
      ],
      callback: res => {
        if (res.name == 'confirm') {
          if (this.data.albumnavcurrent == 1) {
            this.removeHistory()
          } else {
            this.delCollect()
          }
          this.Dialog.CloseDialog();
        } else {
          this.Dialog.CloseDialog();
        }
      }
    })
  },
  removeHistory() {
    var ids = this.data.ids.split(",");
    Controller.removeHistory({
      ids: ids
    }).then(res => {
      this.Dialog.ShowDialog({
        type: 'Message',
        title: '移除成功！'
      });
      this.historyList()
    })
  },
  delCollect() {
    var ids = this.data.ids.join(",");
    console.log('this.data.ids', this.data.ids, ids)

    Controller.delPlayCollect({
      ids: ids
    }).then(res => {
      this.Dialog.ShowDialog({
        type: 'Message',
        title: '取消成功！'
      });
      this.historyList()
    })
  },
  // 单选
  select(e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var ids = this.data.ids;
    if (this.data.audioListdata[index].select == 1) {
      this.data.audioListdata[index].select = 0
      ids.splice(index, 1);
    } else {
      this.data.audioListdata[index].select = 1
      ids.push(id)
    }
    this.setData({
      ids: ids,
      audioListdata: this.data.audioListdata
    })
  },
  // 全选
  alldelete() {
    var ids = []
    var isallselect = this.data.isallselect
    if (!isallselect) {
      for (let item of this.data.audioListdata) {
        item.select = 1
        if (this.data.albumnavcurrent = 1) {
          ids.push(item.historyId)
        } else {
          ids.push((item.rid + '-' + item.type + '-' + item.id))
        }
      }
      isallselect = true
    } else {
      ids = []
      for (let item of this.data.audioListdata) {
        item.select = 0
      }
      isallselect = false
    }
    this.setData({
      ids: ids,
      audioListdata: this.data.audioListdata,
      isallselect: isallselect
    })
  },
  isselect() {
    this.setData({
      isselect: !this.data.isselect
    })
  },
  share(e) {
    // app.share(this.data.userInfodata.id, 1,this.data.userInfodata.nick) 
    wx.navigateTo({
      url: '/pages/PersonalCenter/BaskInTheSun/BaskInTheSun?type=1&nick=' + this.data.userInfodata.nick + '&weekRank=' + this.data.userInfodata.weekRank + '&monthRank=' + this.data.userInfodata.monthRank + '&allTime=' + this.data.userInfodata.listenTimes,
    })
  },
  follow(e) {
    Controller.follow({
      followedUserId: this.data.userId
    }).then(res => {
      this.Dialog.ShowDialog({
        type: 'Message',
        title: '关注成功！'
      });
      this.data.userInfodata.followed = 1
      this.setData({
        userInfodata: this.data.userInfodata
      })
    }).catch(res => {
      if (res.code = -1) {
        this.data.userInfodata.followed = 1
        this.setData({
          userInfodata: this.data.userInfodata
        })
      }
    })
  },
  delFollow(e) {
    Controller.delFollow({
      followedUserIds: this.data.userId
    }).then(res => {
      this.Dialog.ShowDialog({
        type: 'Message',
        title: '取消关注成功！'
      });
      this.data.userInfodata.followed = 0
      this.setData({
        userInfodata: this.data.userInfodata
      })
    }).catch(res => {
      if (res.code = -1) {
        this.data.userInfodata.followed = 0
        this.setData({
          userInfodata: this.data.rankPagedata
        })
      }
    })
  },
  mvlook(e){
    wx.navigateTo({
      url: '/pages/weixinlink/weixinlink?url='+e.currentTarget.dataset.url
    })
  },
  mvmin(e){
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.id,
      path: e.currentTarget.dataset.path,
      extraData: {},
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },
  _init() {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    this._getPlayUrl(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    console.log('currentSong',currentSong)
    if (currentSong && currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      const manage = wx.getBackgroundAudioManager()
      manage.stop()
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {
    wx.playBackgroundAudio({
      dataUrl: currentSong.audioUrl,
      title: currentSong.title,
      coverImgUrl: currentSong.imgUrl
    })
    // 监听音乐播放。
    wx.onBackgroundAudioPlay(() => {
      this.setData({
        play: 2
      })
      app.currentSong=currentSong
      app.play(currentSong.id)
    })
    // 监听音乐暂停。
    wx.onBackgroundAudioPause(() => {
      this.setData({
        play: 1
      })
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
    })
    // 监听音乐停止。
    wx.onBackgroundAudioStop(() => {
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init()
        return
      }
      // 更新收听时长接口
      Controller.uploadListenTimes({
        seconds: parseInt(this.data.currentTime)
      })
      .then(res => {

      })
      this.next()
    })
  },
  onTimeUpdate(time){
    // 监听播放拿取播放进度
    const manage = wx.getBackgroundAudioManager()
    if(time){
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration=manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration:this._formatTime(duration),
        percent: currentTime / duration*100
      })
    })
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init()
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init()
  },
  getNextIndex(nextFlag) {
    let ret,
        currentIndex = app.globalData.currentIndex,
        mod = this.data.playMod,
        len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    wx.getBackgroundAudioPlayerState({
      success(res) {
        var status = res.status
        if (status == 1) {
          wx.pauseBackgroundAudio()
        } else {
          wx.playBackgroundAudio()
        }
      }
    })
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·达人主页',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM·达人主页',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
})